package net.ufrog.common.spring.fastjson;

import net.ufrog.common.spring.exception.ExceptionResolver;
import net.ufrog.common.spring.app.SpringWebApp;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-02-03
 * @since 0.1
 */
public class FastJsonView extends AbstractView {

    @Override
    protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        FastJsonpHttpMessageConverter fastJsonpHttpMessageConverter = SpringWebApp.getBean(FastJsonpHttpMessageConverter.class);
        HttpOutputMessage httpOutputMessage = new ServletServerHttpResponse(httpServletResponse);
        Object model = map.getOrDefault(ExceptionResolver.KEY_MODEL_EXCEPTION, map);

        fastJsonpHttpMessageConverter.write(model, new MediaType("application", "json"), httpOutputMessage);
    }
}
